//*****************************************************************************
// JFab (http://code.google.com/p/jfab)
// Copyright (c) 2011-2012 JFab.org
// Admin jfab@jeffreythompson.net
//
// See the file "LICENSE.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//*****************************************************************************

package org.jfab.core.formatter;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang3.StringUtils;

/**
 * Provides a formatter for an XML file.
 * <p>
 * Inspired by <a href="http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java">StackOverflow</a>
 * </p>
 */
public class XMLFormatter implements Formatter
{
    @Override
    public String format(final String sourceCode)
    {
        String answer = sourceCode;

        if (StringUtils.isNotEmpty(sourceCode))
        {
            try
            {
                final TransformerFactory factory = TransformerFactory.newInstance();
                factory.setAttribute("indent-number", 4);

                final Transformer transformer = factory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                final StreamSource source = new StreamSource(new StringReader(sourceCode));
                final StreamResult result = new StreamResult(new StringWriter());

                transformer.transform(source, result);

                answer = result.getWriter().toString();
            }
            catch (final TransformerConfigurationException e)
            {
                throw new RuntimeException(e);
            }
            catch (final TransformerFactoryConfigurationError e)
            {
                throw new RuntimeException(e);
            }
            catch (final TransformerException e)
            {
                throw new RuntimeException(e);
            }
        }

        return answer;
    }
}
